﻿using HalconDotNet;
using Halcon二次开发.Model;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.工具区域的扩展类;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.Tools;
using Halcon二次开发.View.图片显示弹窗;
using Halcon二次开发.View.多模板匹配;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Shapes;
using System.Xml.Linq;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.MonthCalendar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolTip;
using Rectangle = System.Drawing.Rectangle;

namespace Halcon二次开发.Controller.多模板匹配
{
    /// <summary>
    /// 模板匹配
    /// </summary>
    public class Shap_S_Matching
    {
        /// <summary>
        /// 矩形2工具包
        /// </summary>
        GenRectangle2 draw;
        /// <summary>
        /// 矩形2工具包
        /// </summary>
        GenCirle drawCirle;
        /// <summary>
        /// 当前图像对象,输入图像
        /// </summary>
        public HObject HideIntputImage;
        /// <summary>
        /// 模板匹配变量
        /// </summary>
        public HTuple HideOutputShapeModel;
        /// <summary>
        /// 输出变量OutRow,OutColumn,OutAngle是实时位置
        /// OutStandardRow，OutStandardColumn是基准位置，根据模板来决定基准
        /// OutHImage是输出处理好之后的图像
        /// </summary>
        public double HideOutputRow;
        public double HideOutputColumn;
        public double HideOutputPhi;
        public double HideOutputStandardRow;
        public double HideOutputStandardColumn;
        public double HideOutputScoreShape;//当前模板的分数 

        public double[] HideOutputArrayRows; //输出数组X
        public double[] HideOutputArrayColumns; //输出数组Y
        public double[] HideOutputArrayPhis; //输出数组角度
        public double[] HideOutputArrayScales; //输出缩放比例
        public double[] HideOutputArrayScores; //输出分数

        /// <summary>
        /// 控件句柄
        /// </summary>
        HDrawingObjectEx region = null;
        /// <summary>
        /// 自定义控件界面
        /// </summary>
        Rectangle2Control rectangle;
        CirleControl cirle;

        /// <summary>
        /// 需要创建模板的时候用的区域
        /// </summary>
        public HObject ROI_Sum = null;
        private H_PMA_S_AlignToolForm pmaForm { get; set; }

        public HwindowFlowNodeUrseControl hwindowFlowNode;

        public Shap_S_Matching(H_PMA_S_AlignToolForm pmaForm,Rectangle2Control rectangle,CirleControl cirle, HwindowFlowNodeUrseControl hwindowFlowNode)
        {
            //获取当前工位
            this.hwindowFlowNode = hwindowFlowNode;
            this.pmaForm = pmaForm;
            //调用工具包-矩形2
            draw = new GenRectangle2();
            drawCirle = new GenCirle();

            this.rectangle = rectangle;
            this.cirle = cirle;
        }

        public Shap_S_Matching()
        {
        }

        /// <summary>
        /// 画圆
        /// </summary>
        /// <param name="hWindon">句柄</param>
        public void DrawCirle()
        {
            //互锁
            draw.ClearObject(hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            CirleControl cirle = (CirleControl)pmaForm.groupBox3.Controls[0];
            double x = double.Parse(cirle.XUpDown.Value + "");
            double y = double.Parse(cirle.YUpDown.Value + "");
            double radius = double.Parse(cirle.RaduisUpDown.Value + "");
            drawCirle.DrawCirle(hwindowFlowNode.hSmartWindowControl1.HalconWindow, x, y, radius, pmaForm.textBox3.Text, cirle.XUpDown, cirle.YUpDown, cirle.RaduisUpDown);
        }
        /// <summary>
        /// 画矩形
        /// </summary>
        /// <param name="hWindon">句柄</param>
        //将矩形的Length存储起来
        private double rectangleHigth = 0;
        private double rectangleLigth = 0;
        public void DrawRectangle2()
        {
            //互锁
            drawCirle.ClearObject(hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            Rectangle2Control rectangle2 = (Rectangle2Control)pmaForm.groupBox3.Controls[0];
            double x = double.Parse(rectangle2.XUpDown.Value + "");
            double y = double.Parse(rectangle2.YUpDown.Value + "");
            double phi = double.Parse(rectangle2.PhiUpDown.Value + "");
            double length1 = double.Parse(rectangle2.Length1UpDown.Value + "");
            double length2 = double.Parse(rectangle2.Length2UpDown.Value + "");
            rectangleHigth = length1;
            rectangleLigth = length2;
            draw.DrawRectangle2(hwindowFlowNode.hSmartWindowControl1.HalconWindow, x, y, phi, length1, length2, pmaForm.textBox3.Text, rectangle2.XUpDown, rectangle2.YUpDown, rectangle2.PhiUpDown, rectangle2.Length1UpDown, rectangle2.Length2UpDown);
        }
        /// <summary>
        /// 保存模板
        /// </summary>
        public void SaveShapeModel(string path)
        {
            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            if (HideOutputShapeModel == null)
            {
                return;
            }
            HOperatorSet.WriteShapeModel(HideOutputShapeModel, path);
        }
        /// <summary>
        /// 创建模板
        /// </summary>
        /// <param name="hWindon">句柄</param>
        //paper是用来决定是创建模板时建立模板的
        private static bool paper = false;
        public void CreatShapeModel()
        {
            HOperatorSet.ClearWindow(hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            HOperatorSet.DispObj(HideIntputImage,hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            HObject ROI_0 = null;
            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }


            //使用涂抹区域
            if (ROI_Sum != null)
            {
                ROI_0 = ROI_Sum;
                HOperatorSet.GenRectangle2(out HObject rectangle, double.Parse(draw.XUpdown.Value + "")
                    , double.Parse(draw.YUpdown.Value + ""), double.Parse(draw.PhiUpdown.Value + "")
                    , double.Parse(draw.Length1Updown.Value + ""), double.Parse(draw.Length2Updown.Value + ""));
                paper = true;
                HOperatorSet.ReduceDomain(HideIntputImage, ROI_Sum, out HObject imageReduced);
                try
                {
                    HOperatorSet.CreateScaledShapeModel(imageReduced, "auto", (new HTuple(-360).TupleRad())
                    , (new HTuple(360).TupleRad()), "auto", 0.9, 1.1, "auto", "auto", "use_polarity",
                    "auto", "auto", out HideOutputShapeModel);
                    ROI_Sum = null;
                }
                catch (HOperatorException e)
                {
                    if (e.GetErrorCode() == 3111)
                    {
                        DrawRectangle2();
                        CreatShapeModel();
                    }
                }
            }
            else
            {
                //获取位置信息,谁有值就执行谁
                draw.GetPoint(out HDrawingObjectEx region1);
                drawCirle.GetPoint(out HDrawingObjectEx region2);
                if (region1 != null)
                {
                    //矩形
                    region = region1;
                    HOperatorSet.GenRectangle2(out ROI_0, region.hTuples[0], region.hTuples[1], region.hTuples[2], region.hTuples[3], region.hTuples[4]);
                    draw.ClearObject(hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                }
                else if (region2 != null)
                {
                    //圆形
                    region = region2;
                    HOperatorSet.GenCircle(out ROI_0, region.hTuples[0], region.hTuples[1], region.hTuples[2]);
                    drawCirle.ClearObject(hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                }

                paper = true;
                if (ROI_0 == null) return;
                HOperatorSet.ReduceDomain(HideIntputImage, ROI_0, out HObject imageReduced);

                try
                {
                    HOperatorSet.CreateScaledShapeModel(imageReduced, "auto", (new HTuple(-360).TupleRad())
                    , (new HTuple(360).TupleRad()), "auto", 0.9, 1.1, "auto", "auto", "use_polarity",
                    "auto", "auto", out HideOutputShapeModel);
                }
                catch (HOperatorException e)
                {
                    if (e.GetErrorCode() == 3111)
                    {
                        DrawRectangle2();
                        CreatShapeModel();
                    }
                }
            }
            HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow,"green");
            HOperatorSet.GetShapeModelContours(out HObject ho_ModelContours, HideOutputShapeModel, 1);
            HOperatorSet.AreaCenter(ROI_0, out HTuple hv_Area, out HTuple hv_Row1, out HTuple hv_Column1);
            //几何变换的实现
            HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DIdentity);
            HOperatorSet.HomMat2dTranslate(hv_HomMat2DIdentity, hv_Row1, hv_Column1, out HTuple hv_HomMat2DTranslate);
            HOperatorSet.HomMat2dRotate(hv_HomMat2DTranslate, 0, hv_Row1, hv_Column1, out HTuple hv_HomMat2DRotate);
            HOperatorSet.HomMat2dScale(hv_HomMat2DRotate, 1, 1, hv_Row1, hv_Column1, out HTuple hv_HomMat2DScale);
            HOperatorSet.AffineTransContourXld(ho_ModelContours, out HObject ho_ContoursAffineTrans, hv_HomMat2DScale);

            HOperatorSet.DispObj(ho_ContoursAffineTrans, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            //创建一个供存储基准数据的文件夹
            Directory.CreateDirectory(pmaForm.standardPath);
        }
        /// <summary>
        /// 寻找模版CreatShape
        /// </summary>
        /// <param name="path">模板路径</param>
        /// <param name="hWindon">句柄</param>
        /// /// <param name="value1">模板匹配的分数下限</param>
        /// /// <param name="value2">模板匹配的分数上限</param>
        public void Run()
        {
            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            //清除模型
            ClearTwoObject(hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            //清除字典存储集合
            //HideOutputResults.Clear();
            pmaForm.dataGridView1.Rows.Clear();
            pmaForm.textBox4.Text = "";
            try
            {
                HOperatorSet.ReadShapeModel(pmaForm.filePath, out HTuple hv_ModelID2);
                HOperatorSet.GetShapeModelContours(out HObject ho_ModeContours, hv_ModelID2, 1);
                if (hv_ModelID2 == null)
                {
                    throw new Exception("寻找模板失败");
                }
                //这里要添加一个搜索区域，去减少模板匹配的搜索时间
                if (pmaForm.comboBox7.SelectedItem.Equals("开启"))
                {
                    try
                    {
                        if (searchArea != null)
                        {
                            searchArea.Dispose();
                            searchArea.ClearDrawingObject();
                        }
                        //生成一个矩形区域
                        HOperatorSet.GenRectangle2(out HObject rectanglephi, (HTuple)pmaForm.numericUpDown21.Value, (HTuple)pmaForm.numericUpDown22.Value, new HTuple((HTuple)pmaForm.numericUpDown23.Value).TupleRad(), (HTuple)pmaForm.numericUpDown24.Value, (HTuple)pmaForm.numericUpDown25.Value);
                        HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "green");
                        HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "margin");
                        HOperatorSet.DispObj(rectanglephi, hwindowFlowNode.hSmartWindowControl1.HalconWindow);

                        HOperatorSet.ReduceDomain(HideIntputImage, rectanglephi, out HObject imageReduced);
                        HideIntputImage = imageReduced;
                    }
                    catch (Exception ex)
                    {
                        (FormDb.Db["Form1"] as Form1).textBox1.AppendText("设置模板匹配搜索区域失败" + ":" + ex.Message + "\r\n");
                    }
                }
                //金字塔层数越高处理速度越快 NumLevels
                //搜索启发式的（0：安全 但速度很慢;1：快速但可能会错过匹配项） Greediness
                HOperatorSet.FindScaledShapeModels(HideIntputImage, hv_ModelID2, (new HTuple(int.Parse(pmaForm.numericUpDown4.Value.ToString()))).TupleRad(), (new HTuple(int.Parse(pmaForm.numericUpDown3.Value.ToString()))).TupleRad(),

                    1, 1, double.Parse(pmaForm.numericUpDown1.Value.ToString()), int.Parse(pmaForm.numericUpDown13.Value.ToString()), double.Parse(pmaForm.numericUpDown7.Value.ToString()), pmaForm.comboBox1.SelectedItem.ToString(), int.Parse(pmaForm.numericUpDown5.Value.ToString()), double.Parse(pmaForm.numericUpDown6.Value.ToString()),

                    out HTuple hv_RowShape, out HTuple hv_ColumnShape, out HTuple hv_AngleShape, out HTuple hv_ScaleShape, out HTuple hv_ScoreShape, out HTuple hv_Model);
               
               
                //记录一下方便后续调用
                if (paper)
                {
                    //点击记录基准数据
                    HideOutputStandardRow = hv_RowShape[0];
                    HideOutputStandardColumn = hv_ColumnShape[0];
                    //将这个基准数据进行保存下来
                    List<double> doubleList = new List<double>();
                    doubleList.Add(HideOutputStandardRow);
                    doubleList.Add(HideOutputStandardColumn);
                    //将这个数据进行持久化
                    HelpJsons.Write<double>(doubleList, pmaForm.standardPath + "\\" + "standar.txt");
                    paper = false;
                }
                //添加给输出  x，y位置，角度
                try
                {
                    //模板匹配失败,将值汇纳为0
                    if (hv_RowShape.Length == 0)
                    {
                        HideOutputRow = 0;
                        HideOutputColumn = 0;
                        HideOutputPhi = 0;

                        HideOutputArrayRows = null;
                        HideOutputArrayColumns = null;
                        HideOutputArrayPhis = null;
                        HideOutputArrayScales = null;
                        HideOutputArrayScores = null;
                        throw new Exception();
                    }
                    HideOutputRow = hv_RowShape[0];
                    HideOutputColumn = hv_ColumnShape[0];
                    HideOutputPhi = hv_AngleShape[0];

                    HideOutputArrayRows = hv_RowShape;
                    HideOutputArrayColumns = hv_ColumnShape;
                    HideOutputArrayPhis = hv_AngleShape;
                    HideOutputArrayScales = hv_ScaleShape;
                    HideOutputArrayScores = hv_ScoreShape;
                }
                catch
                {
                    throw new Exception("寻找模板失败");
                }
                //判断是否在分数内
                if (hv_ScoreShape > (double)pmaForm.numericUpDown1.Value)
                {
                    HOperatorSet.TupleLength(hv_RowShape, out HTuple count);
                    for (int i = 0; i < hv_RowShape.Length; i++)
                    {
                        HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DIdentity);
                        HOperatorSet.HomMat2dTranslate(hv_HomMat2DIdentity, hv_RowShape[i], hv_ColumnShape[i], out HTuple hv_HomMat2DTranslate);
                        HOperatorSet.HomMat2dRotate(hv_HomMat2DTranslate, hv_AngleShape[i], hv_RowShape[i], hv_ColumnShape[i],
                            out HTuple hv_HomMat2DRotate);
                        HOperatorSet.HomMat2dScale(hv_HomMat2DRotate, hv_ScaleShape[i], hv_ScaleShape[i], hv_RowShape[i], hv_ColumnShape[i],
                            out HTuple hv_HomMat2DScale);

                        HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "green");


                        HOperatorSet.AffineTransContourXld(ho_ModeContours, out HObject ho_AffineTransContour, hv_HomMat2DScale);
                        HOperatorSet.DispObj(ho_AffineTransContour, hwindowFlowNode.hSmartWindowControl1.HalconWindow);

                        //sort_region
                        pmaForm.dataGridView1.Rows.Add(i, hv_RowShape[i].D, hv_ColumnShape[i].D, hv_AngleShape[i].D, hv_ScaleShape[i].D, hv_ScoreShape[i].D);
                    }
                }
                else
                {
                    pmaForm.textBox4.Text = "丢失分数为: " + hv_ScoreShape;
                    throw new Exception("匹配失败");
                }
                //将我们的模板匹配的分数给到输出接口
                HideOutputScoreShape = hv_ScoreShape;

                
            }
             catch(Exception ex)
            {
                string str = string.Empty;
                if (ex.Message.Contains("匹配失败!"))
                {
                    str = "匹配失败!";
                }
                else if (ex.Message.Contains("寻找模板失败!"))
                {
                    str = "寻找模板失败!";
                }
                else if (ex.Message.Contains("样品不合格,间距匹配失败"))
                {
                    str = "样品不合格,间距匹配失败";
                }
                else
                {
                    str = "模板匹配运行失败，请检查你的模板是否正确!";
                }
                throw new Exception(str);


            }
        }
        /// <summary>
        /// 计量模型移动方法
        /// </summary>
        public void Move(Object sender)
        {
            System.Windows.Forms.NumericUpDown number = (sender as System.Windows.Forms.NumericUpDown);
            UserControl control = (UserControl)number.Parent;
            if (control.Name == "Rectangle2Control")
            {
                Rectangle2Control rectangle = (Rectangle2Control)number.Parent;
                if (rectangle != null)
                {
                    draw.Move(hwindowFlowNode.hSmartWindowControl1.HalconWindow, double.Parse(rectangle.XUpDown.Value + ""), double.Parse(rectangle.YUpDown.Value + ""), double.Parse(rectangle.PhiUpDown.Value + ""), double.Parse(rectangle.Length1UpDown.Value + "")
                        , double.Parse(rectangle.Length2UpDown.Value + ""), pmaForm.textBox3.Text);
                }
            }
            else if (control.Name == "CirleControl")
            {
                CirleControl cirle = (CirleControl)number.Parent;
                if (control != null)
                {
                    drawCirle.Move(hwindowFlowNode.hSmartWindowControl1.HalconWindow, double.Parse(cirle.XUpDown.Value + ""), double.Parse(cirle.YUpDown.Value + ""), double.Parse(cirle.RaduisUpDown.Value + ""), pmaForm.textBox3.Text);
                }
            }
        }
        public void ClearTwoObject(HWindow hWindon)
        {
            //清除模型
            if (draw != null)
            {
                draw.ClearObject(hWindon);
            }

            if (drawCirle != null)
            {
                drawCirle.ClearObject(hWindon);
            }
        }
        /// <summary>
        /// 工具的单次运行
        /// </summary>
        public void Tool_Run()
        {
            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            hwindowFlowNode.hSmartWindowControl1.HalconWindow.ClearWindow();
            HOperatorSet.DispObj(HideIntputImage, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            Run();
        }
        /// <summary>
        /// 搜索区域
        /// </summary>
        public HDrawingObject searchArea;
        public void DrawSearch()
        {
            searchArea = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.RECTANGLE2, new HTuple[] { 50,100,0,50,50});
            //线段拖动触发事件注册
            searchArea.OnDrag(RectangleDrawResize);
            //线段长度修改触发事件注册
            searchArea.OnResize(RectangleVerifyResize);
            hwindowFlowNode.hSmartWindowControl1.HalconWindow.AttachDrawingObjectToWindow(searchArea);
        }

        private void RectangleDrawResize(HDrawingObject drawid, HWindow window, string type)
        {
            RectangleDrawSearch(drawid);
        }
        private void RectangleVerifyResize(HDrawingObject drawid, HWindow window, string type)
        {
            RectangleDrawSearch(drawid);
        }
        /// <summary>
        /// 矩形拖动或者修改时触发该事件
        /// </summary>
        /// <param name="drawid"></param>
        private void RectangleDrawSearch(HDrawingObject drawid)
        {
            //
            //创建一个要得到对象属性的元组
            var attTuple = new HTuple("row", "column", "phi", "length1", "length2");
            //获取对应的属性
            var valueTuple = drawid.GetDrawingObjectParams(attTuple);
            //将矩形的坐标给到控件
            pmaForm.numericUpDown21.Value = (decimal)valueTuple[0].D;
            pmaForm.numericUpDown22.Value = (decimal)valueTuple[1].D;
            HTuple hTuple = new HTuple(valueTuple[2].D).TupleDeg();
            pmaForm.numericUpDown23.Value = (decimal)hTuple.D;
            pmaForm.numericUpDown24.Value = (decimal)valueTuple[3].D;
            pmaForm.numericUpDown25.Value = (decimal)valueTuple[4].D;
        }
        /// <summary>
        /// 硬触发模板匹配
        /// </summary>
        public void HardRun(HObject HideIntputImage,string filePath,H_PMA_S_AlignToolForm pmaForm, HDrawingObject searchArea, HSmartWindowControl hSmartWindowControl,ref double[] HideOutputArrayRows,ref double[] HideOutputArrayColumns,ref double[] HideOutputArrayPhis)
        {
            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            //清除模型
            //ClearTwoObject(hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            //清除字典存储集合
            //HideOutputResults.Clear();
            //pmaForm.dataGridView1.Rows.Clear();
            //pmaForm.textBox4.Text = "";
            try
            {
                HOperatorSet.ReadShapeModel(filePath, out HTuple hv_ModelID2);
                HOperatorSet.GetShapeModelContours(out HObject ho_ModeContours, hv_ModelID2, 1);
                if (hv_ModelID2 == null)
                {
                    throw new Exception("寻找模板失败");
                }
                //这里要添加一个搜索区域，去减少模板匹配的搜索时间
                if (pmaForm.comboBox7.SelectedItem.Equals("开启"))
                {
                    try
                    {
                        if (searchArea != null)
                        {
                            searchArea.Dispose();
                            searchArea.ClearDrawingObject();
                        }
                        //生成一个矩形区域
                        HOperatorSet.GenRectangle2(out HObject rectanglephi, (HTuple)pmaForm.numericUpDown21.Value, (HTuple)pmaForm.numericUpDown22.Value, new HTuple((HTuple)pmaForm.numericUpDown23.Value).TupleRad(), (HTuple)pmaForm.numericUpDown24.Value, (HTuple)pmaForm.numericUpDown25.Value);
                        HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "green");
                        HOperatorSet.SetDraw(hSmartWindowControl.HalconWindow, "margin");
                        HOperatorSet.DispObj(rectanglephi, hSmartWindowControl.HalconWindow);

                        HOperatorSet.ReduceDomain(HideIntputImage, rectanglephi, out HObject imageReduced);
                        HideIntputImage = imageReduced;
                    }
                    catch (Exception ex)
                    {
                        (FormDb.Db["Form1"] as Form1).textBox1.AppendText("设置模板匹配搜索区域失败" + ":" + ex.Message + "\r\n");
                    }
                }
                //金字塔层数越高处理速度越快 NumLevels
                //搜索启发式的（0：安全 但速度很慢;1：快速但可能会错过匹配项） Greediness
                HOperatorSet.FindScaledShapeModels(HideIntputImage, hv_ModelID2, (new HTuple(int.Parse(pmaForm.numericUpDown4.Value.ToString()))).TupleRad(), (new HTuple(int.Parse(pmaForm.numericUpDown3.Value.ToString()))).TupleRad(),

                    1, 1, double.Parse(pmaForm.numericUpDown1.Value.ToString()), int.Parse(pmaForm.numericUpDown13.Value.ToString()), double.Parse(pmaForm.numericUpDown7.Value.ToString()), pmaForm.comboBox1.SelectedItem.ToString(), int.Parse(pmaForm.numericUpDown5.Value.ToString()), double.Parse(pmaForm.numericUpDown6.Value.ToString()),

                    out HTuple hv_RowShape, out HTuple hv_ColumnShape, out HTuple hv_AngleShape, out HTuple hv_ScaleShape, out HTuple hv_ScoreShape, out HTuple hv_Model);
                //添加给输出  x，y位置，角度
                try
                {
                    //模板匹配失败,将值汇纳为0
                    if (hv_RowShape.Length == 0)
                    {
                        HideOutputArrayRows = null;
                        HideOutputArrayColumns = null;
                        HideOutputArrayPhis = null;
                        HideOutputArrayScales = null;
                        HideOutputArrayScores = null;
                        throw new Exception();
                    }
                    HideOutputArrayRows = hv_RowShape;
                    HideOutputArrayColumns = hv_ColumnShape;
                    HideOutputArrayPhis = hv_AngleShape;
                    HideOutputArrayScales = hv_ScaleShape;
                    HideOutputArrayScores = hv_ScoreShape;
                }
                catch
                {
                    throw new Exception("寻找模板失败");
                }
                //判断是否在分数内
                if (hv_ScoreShape > (double)pmaForm.numericUpDown1.Value)
                {
                    HOperatorSet.TupleLength(hv_RowShape, out HTuple count);
                    for (int i = 0; i < hv_RowShape.Length; i++)
                    {
                        HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DIdentity);
                        HOperatorSet.HomMat2dTranslate(hv_HomMat2DIdentity, hv_RowShape[i], hv_ColumnShape[i], out HTuple hv_HomMat2DTranslate);
                        HOperatorSet.HomMat2dRotate(hv_HomMat2DTranslate, hv_AngleShape[i], hv_RowShape[i], hv_ColumnShape[i],
                            out HTuple hv_HomMat2DRotate);
                        HOperatorSet.HomMat2dScale(hv_HomMat2DRotate, hv_ScaleShape[i], hv_ScaleShape[i], hv_RowShape[i], hv_ColumnShape[i],
                            out HTuple hv_HomMat2DScale);

                        HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "green");

                        HOperatorSet.AffineTransContourXld(ho_ModeContours, out HObject ho_AffineTransContour, hv_HomMat2DScale);
                        HOperatorSet.DispObj(ho_AffineTransContour, hSmartWindowControl.HalconWindow);

                    }
                }
                else
                {
                    pmaForm.textBox4.Text = "丢失分数为: " + hv_ScoreShape;
                    throw new Exception("匹配失败");
                }
                //将我们的模板匹配的分数给到输出接口
                HideOutputScoreShape = hv_ScoreShape;


            }
            catch (Exception ex)
            {
                string str = string.Empty;
                if (ex.Message.Contains("匹配失败!"))
                {
                    str = "匹配失败!";
                }
                else if (ex.Message.Contains("寻找模板失败!"))
                {
                    str = "寻找模板失败!";
                }
                else if (ex.Message.Contains("样品不合格,间距匹配失败"))
                {
                    str = "样品不合格,间距匹配失败";
                }
                else
                {
                    str = "模板匹配运行失败，请检查你的模板是否正确!";
                }
                throw new Exception(str);
            }
        }

        //鼠标右击的确认
        public bool MouseRight = true;
        bool Smear_OK;
        /// <summary>
        /// 涂抹
        /// </summary>
        public void Smear() {
            pmaForm.toolStripButton6.Enabled = false;
            pmaForm.toolStripButton2.Enabled = false;
            pmaForm.toolStripButton5.Enabled = false;
            pmaForm.toolStripButton3.Enabled = false;
            hwindowFlowNode.contextMenuStrip1.Items.Add("确认ROI");
            hwindowFlowNode.contextMenuStrip1.Items[hwindowFlowNode.contextMenuStrip1.Items.Count-1].MouseDown += Shap_S_Matching_MouseDown;

            HObject ROI_0 = null;
            //hwindowFlowNode.hSmartWindowControl1.MouseWheel -= hwindowFlowNode.HSmartWindowControl1_MouseWheel;

            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            hwindowFlowNode.hSmartWindowControl1.HMoveContent = false;
            if (ROI_Sum != null)
            {
                ROI_0 = ROI_Sum;
            }
            else
            {
                //获取位置信息,谁有值就执行谁
                draw.GetPoint(out HDrawingObjectEx region1);
                drawCirle.GetPoint(out HDrawingObjectEx region2);
                if (region1 != null)
                {
                    //矩形
                    region = region1;
                    HOperatorSet.GenRectangle2(out ROI_0, region.hTuples[0], region.hTuples[1], region.hTuples[2], region.hTuples[3], region.hTuples[4]);
                }
                else if (region2 != null)
                {
                    //圆形
                    region = region2;
                    HOperatorSet.GenCircle(out ROI_0, region.hTuples[0], region.hTuples[1], region.hTuples[2]);
                }
                if (region == null) return;
                hwindowFlowNode.hSmartWindowControl1.HalconWindow.DetachDrawingObjectFromWindow(region.HDrawingObject);
            }

            //创建RIO的区域
            HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "fill");
            HOperatorSet.SetRgba(hwindowFlowNode.hSmartWindowControl1.HalconWindow, 0, 0, 255, 180);
            HOperatorSet.DispObj(ROI_0, hwindowFlowNode.hSmartWindowControl1.HalconWindow);

            //先创建一个移除区域
            HOperatorSet.GenEmptyObj(out HObject Region_Removeds);
            //先创建一个保留区域
            HOperatorSet.GenEmptyObj(out HObject Region_Reserveds);
            //循环等待擦除，右键结束
            Task.Run(() =>
            {
                while (MouseRight)
                {
                    //pmaForm.toolStripButton6.Enabled = false;
                    //获取计算机鼠标信息
                    try
                    {
                        HOperatorSet.SetCheck("~give_error");
                        //HOperatorSet.GetMposition(hwindowFlowNode.hSmartWindowControl1.HalconWindow, out HTuple row, out HTuple col, out HTuple button);
                        HOperatorSet.SetCheck("give_error");
                        if (Smear_OK)
                        {
                            pmaForm.toolStripButton6.Enabled = true;
                            pmaForm.toolStripButton2.Enabled = true;
                            pmaForm.toolStripButton5.Enabled = true;
                            pmaForm.toolStripButton3.Enabled = true;
                            Smear_OK = false;
                            MouseRight = false;
                            hwindowFlowNode.hSmartWindowControl1.HMoveContent = true;
                            //hwindowFlowNode.hSmartWindowControl1.MouseWheel += hwindowFlowNode.HSmartWindowControl1_MouseWheel;
                            hwindowFlowNode.contextMenuStrip1.Items[1].MouseDown -= Shap_S_Matching_MouseDown;
                            hwindowFlowNode.contextMenuStrip1.Items.RemoveAt(hwindowFlowNode.contextMenuStrip1.Items.Count - 1);
                            ROI_Sum = Region_Reserveds;
                            MessageBox.Show("涂抹成功!", "提示");
                            return;
                        }
                        HOperatorSet.SetCheck("give_error");

                        if (hwindowFlowNode.button == MouseButtons.Left)
                        {
                            HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "margin");
                            HOperatorSet.GenCircle(out HObject circle, hwindowFlowNode.mouse_row, hwindowFlowNode.mouse_col, int.Parse(pmaForm.smearSize.Value + ""));
                            HOperatorSet.Union2(Region_Removeds, circle, out Region_Removeds);
                            HOperatorSet.Difference(ROI_0, Region_Removeds, out Region_Reserveds);
                            HOperatorSet.DispObj(HideIntputImage, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                            HOperatorSet.SetDraw(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "fill");
                            HOperatorSet.SetRgba(hwindowFlowNode.hSmartWindowControl1.HalconWindow, 0, 0, 255, 180);
                            HOperatorSet.DispRegion(Region_Reserveds, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                        }
                    }
                    catch (Exception ex){
                        Smear_OK = false;
                        MouseRight = false;
                        hwindowFlowNode.hSmartWindowControl1.HMoveContent = true;
                        hwindowFlowNode.hSmartWindowControl1.MouseWheel += hwindowFlowNode.HSmartWindowControl1_MouseWheel;
                        hwindowFlowNode.contextMenuStrip1.Items[1].MouseDown -= Shap_S_Matching_MouseDown;
                        hwindowFlowNode.contextMenuStrip1.Items.RemoveAt(hwindowFlowNode.contextMenuStrip1.Items.Count - 1);
                    }
                }
            });
        }

        private void Shap_S_Matching_MouseDown(object sender, MouseEventArgs e)
        {
            Smear_OK = true;
        }
    }
}